package org.jtb.quickr;

import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;

class ApiSignature {
    private static Logger logger = Logger.getLogger(ApiSignature.class.getName());
    
    private String signature;
    
    public ApiSignature(String secret, Map<String,String> args) {
        this.setSignature(buildSignature(secret, args));
    }
    
    private static String buildSignature(String secret, Map<String,String> args) {
        StringBuffer b = new StringBuffer(32);
        b.append(secret);
        
        SortedMap<String,String> sargs = new TreeMap<String,String>(args);
        for (Iterator<String> i = sargs.keySet().iterator(); i.hasNext(); ) {
            String key = i.next();
            String val = sargs.get(key);
            b.append(key);
            b.append(val);
        }
        
        String s = b.toString();
        String sig = DigestUtils.md5Hex(s);
        
        if (logger.isDebugEnabled()) {
            logger.debug("string to sign: " + s);
            logger.debug("signature: " + sig);
        }
        
        return sig;
    }
    
    public String getSignature() {
        return signature;
    }
    
    private void setSignature(String signature) {
        this.signature = signature;
    }
    
}
